﻿using System;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Collections.Generic;
using ZX.EHR.Library;
using ZX.BLL;
using System.Data;
using System.ServiceModel.Description;
using System.ServiceModel;
using ZX.WebApp.WebControls;
using WcfSamples.DynamicProxy;
using ZX.CRM.Bussiness;
using ZX.CRM.Library;


namespace ZX.WebApp.Crm.BasePages
{
	public partial class WorkflowDataManager: ZX.Web.UI.Controls.BasePage
	{
        
		protected void Page_Load(object sender, EventArgs e)
		{

		}
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string WorkFlowStatr(string TableName, object KeyValue, string xWorkflowId, string xWorktaskId, string xTitle, string IsDraft)
        {
          
            string strWorkMsg = "";
            bool isdraft = false;
            try
            {
                if (!string.IsNullOrEmpty(TableName) && KeyValue != null)
                {

                    if (TableName != "" && KeyValue != null)
                    {
                        ZX.EHR.Library.DatUser U = HttpContext.Current.Session["User"] as ZX.EHR.Library.DatUser;
                        ZX.WebApp.CrmWorkFlowService.WorkFlowEntity WFentity = new CrmWorkFlowService.WorkFlowEntity();
                        ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                        string UserId = U.LoginName.ToString();
                        string WorkflowInsId = HttpContext.Current.Session["workinsid"].ToString();
                        string WorktaskInsId = HttpContext.Current.Session["worktasid"].ToString();
                        WFentity = client.GetWorkFlowEntity(xWorkflowId);
                        if (string.IsNullOrEmpty(xTitle))
                        {
                            xTitle = WFentity.FlowCaption;
                        }
                        if (IsDraft == "1")
                        {
                            isdraft = true;
                        }
                        ZX.SYS.Bussiness.WorkFlowStartInfo wfsi = new ZX.SYS.Bussiness.WorkFlowStartInfo();

                        if (wfsi.Start(TableName, KeyValue, xWorkflowId, xWorktaskId, WorktaskInsId, WorkflowInsId))
                        {
                            //Response.Write("更新成功");
                            ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient workflow = new ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient();
                            workflow.Start(UserId, xWorkflowId.ToString(), xWorktaskId.ToString(), WorkflowInsId.ToString(), WorktaskInsId.ToString(), workflow.GetWorkFlowNO(), "提交", "3", xTitle, isdraft);
                            if (isdraft)
                            {
                                strWorkMsg = "OK%123@";
                            }
                            else
                            {
                                strWorkMsg = "OK%@" + WorktaskInsId;
                            }
                            
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                strWorkMsg = "ERR%@" + ex.Message;
            }

            return strWorkMsg;
        }


        /// <summary>
        /// 不定期
        /// </summary>
        /// <param name="xWorkflowId"></param>
        /// <param name="xWorktaskId"></param>
        /// <param name="xValues"></param>
        /// <param name="xNames"></param>
        /// <returns></returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string FreeFlow(string xWorkflowId, string xWorktaskId, string xValues, string xNames) 
        {
            string strWorkMsg = "";
            try
            {
                //ZX.WebApp.CrmWorkFlowService.WorkFlowEntity WFentity = new CrmWorkFlowService.WorkFlowEntity();
                ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                string WorkflowInsId = HttpContext.Current.Session["workinsid"].ToString();
                string WorktaskInsId = HttpContext.Current.Session["worktasid"].ToString();
                client.WorkFlowOrderType(xValues, xNames, xWorkflowId, xWorktaskId, WorkflowInsId, WorktaskInsId);
                strWorkMsg = "OK%@";
            }
            catch (Exception ex)
            {
                strWorkMsg = "ERR%@" + ex.Message;
            }
            return strWorkMsg;
        }

        /// <summary>
        /// 提交流程事件
        /// </summary>
        /// <param name="OperatorInsId"></param>
        /// <param name="commandName"></param>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string RunEvent(string OperatorInsId,string commandName)
        {
            string strWorkMsg = "";
            ZX.EHR.Library.DatUser U = HttpContext.Current.Session["User"] as ZX.EHR.Library.DatUser;
            string UserId = U.LoginName.ToString();
            try
            {
                
                ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                DataTable dt = client.GetOperatorInstanceView(OperatorInsId);   //todo zhuyun 20121012
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["OperType"].ToString() == "12")
                    {
                        client.SetWorkTaskInsStatus(dt.Rows[0]["WorkTaskInstanceId"].ToString());
                        client.SetOperatorInstance(UserId, dt.Rows[0]["WorkTaskInstanceId"].ToString());
                        strWorkMsg = "OK%@";
                    }
                    else
                    {
                        client.TaskClaim(UserId, OperatorInsId);   // 认领操作
                        string strMsg = client.Run(UserId, OperatorInsId, commandName);
                        strWorkMsg = "OK%@" + strMsg;
                        //if (strMsg == "000000") //流程返回结果
                        //{
                        //    //对比是否触发流程规则 
                        //    DataTable table = client.ContrastLoad(dt.Rows[0]["WorkFlowInstanceId"].ToString(), dt.Rows[0]["FlowCaption"].ToString(), dt.Rows[0]["WorkFlowId"].ToString());
                        //    if (table != null && table.Rows.Count > 0)
                        //    {
                        //        InvokeSimpleCalculator(table, dt);
                        //    }
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                strWorkMsg = "ERR%@" + ex.Message;
            }
            return strWorkMsg;
             //Response.Redirect("tooltip.aspx?worktaskInstanceId=" + WorktaskInsId);
            
        }


        /// <summary>
        /// 更新标题
        /// </summary>
        /// <param name="workFlowInstanceId"></param>
        /// <param name="title"></param>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string UpdateTitle(string workFlowInstanceId, string title)
        {
            string strWorkMsg = "";
           
            try
            {
                    ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                    client.UpdateTitle(workFlowInstanceId, title);   // 更新标题
                    strWorkMsg = "OK%@";
            }
            catch (Exception ex)
            {
                strWorkMsg = "ERR%@" + ex.Message;
            }
            return strWorkMsg;
            
        }
       

        public static void InvokeSimpleCalculator(DataTable table, DataTable dt)
        {
            DynamicProxyFactory factory = new DynamicProxyFactory(table.Rows[0]["Address"].ToString());
            ServiceEndpoint serviceEndpoint = factory.GetEndpoint(table.Rows[0]["Iserver"].ToString());
            ((BasicHttpBinding)(serviceEndpoint.Binding)).MaxBufferSize = int.MaxValue;

            ((BasicHttpBinding)(serviceEndpoint.Binding)).MaxReceivedMessageSize = int.MaxValue;

            ((BasicHttpBinding)(serviceEndpoint.Binding)).ReaderQuotas.MaxArrayLength = int.MaxValue;

            ((BasicHttpBinding)(serviceEndpoint.Binding)).ReaderQuotas.MaxBytesPerRead = int.MaxValue;

            ((BasicHttpBinding)(serviceEndpoint.Binding)).ReaderQuotas.MaxDepth = int.MaxValue;

            ((BasicHttpBinding)(serviceEndpoint.Binding)).ReaderQuotas.MaxNameTableCharCount = int.MaxValue;

            ((BasicHttpBinding)(serviceEndpoint.Binding)).ReaderQuotas.MaxStringContentLength = int.MaxValue;

            DynamicProxy simpleCalculatorProxy = factory.CreateProxy(table.Rows[0]["Iserver"].ToString());
            FlowXmlDefine flowXml = new FlowXmlDefine();
            string MsgLinkUrl = string.Empty;
            AppFunc appFunc = flowXml.ListSystemFunc(table.Rows[0]["AppSystem"].ToString(), table.Rows[0]["AppModel"].ToString(), MsgLinkUrl);
            string[] args;
            if (appFunc.Parameter.Count > 0)
            {
                args = new string[appFunc.Parameter.Count];
            }
            else
            {
                args = null;
            }
            if (appFunc != null)
            {
                for (int i = 0; i < appFunc.Parameter.Count; i++)
                {
                    if (appFunc.Parameter[i].Sataus == "1")
                    {
                        if (dt.Columns.Contains(appFunc.Parameter[i].Name))
                        {
                            args[i] = dt.Rows[0][appFunc.Parameter[i].Name].ToString();
                        }
                    }
                    else
                    {
                        args[i] = appFunc.Parameter[i].Value;
                    }
                }
            }
            simpleCalculatorProxy.CallMethod(table.Rows[0]["MethodName"].ToString(), args);

        }
        /// <summary>
        /// 任务退回事件
        /// </summary>
        /// <param name="OperatorInsId"></param>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string taskBackButtonEvent(string OperatorInsId)
        {
             string strWorkMsg = "";
             try
             {
                 ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                 ZX.EHR.Library.DatUser U = HttpContext.Current.Session["User"] as ZX.EHR.Library.DatUser;
                 string UserId = U.LoginName.ToString();
                 client.TaskClaim(UserId, OperatorInsId);   // 认领操作
                 strWorkMsg = client.TaskBackApplicant(UserId, OperatorInsId);
             }
             catch (Exception ex)
             {
                 strWorkMsg = "ERR%@" + ex.Message;
             }
     
             //Response.Redirect("tooltip.aspx?worktaskInstanceId=" + WorktaskInsId);
            return strWorkMsg;
        }
        /// <summary>
        /// 根据任务配置加载流程命令按钮
        /// </summary>
        /// <param name="WorktaskId"></param>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string GetCommandsButton(string WorktaskId)
        {
            string strTableList = "";
             try
             {
            //DataTable taskCommand = client.GetTaskCommands(WorktaskId);
            //foreach (DataRow dr in taskCommand.Rows)
            //{
            //    string cmdName = dr["CommandName"].ToString();
            //    Button btnCommand = new Button();
            //    btnCommand.Enabled = (pageState != WorkFlowConst.STATE_VIEW && OperStatus != "0");
            //    btnCommand.Text = cmdName;
            //    btnCommand.Click += new EventHandler(runButtonEvent);
            //    cmdBtnPlace.Controls.Add(btnCommand);
            //    Literal lab1 = new Literal();
            //    lab1.Text = "&nbsp;&nbsp;";
            //    cmdBtnPlace.Controls.Add(lab1);
            //}
                ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                System.Data.DataTable taskCommand = client.GetTaskCommands(WorktaskId);
                 if (taskCommand.Rows.Count > 0)
                 {
                     strTableList = ZX.Common.Globals.Dtb2Json(taskCommand);
                 }
             }
             catch (Exception ex)
             {
                 strTableList = "ERR%@" + ex.Message;
             }

             //Response.Redirect("tooltip.aspx?worktaskInstanceId=" + WorktaskInsId);
             return strTableList;
        }
        /// <summary>
        /// 指派任务，指派人 
        /// </summary>
        /// <param name="WorktaskId"></param>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string GetWorkTaskAssign(string assignUser, string operatorInsId, string worktaskInsId)
        {
            string msg="";
            try
            {
                BUser bUser = new BUser();
                DatUser dus = bUser.GetDatUserByUserId(new Guid(assignUser));
                ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                ZX.EHR.Library.DatUser U = HttpContext.Current.Session["User"] as ZX.EHR.Library.DatUser;
                string testmsg=client.TaskClaim(U.LoginName.ToString(), operatorInsId);  
                msg=client.WorkTaskAssign(U.LoginName.ToString(), dus == null ? "" : dus.LoginName, operatorInsId);
                DataTable dt = client.GetOperatorInstanceView(operatorInsId);
                msg="OK%@"+dt.Rows[0]["PreviousTaskInstanceId"].ToString();
            }
            catch (Exception ex)
            {
                msg = "Err%@" + ex.Message;               
            }
            //Response.Redirect("tooltip.aspx?worktaskInstanceId=" + worktaskInsId);
            return msg;
        }

        /// <summary>
        /// 判断流程是否是退回
        /// </summary>
        /// <param name="OperatorInsId"></param>
        /// <returns>返回状态</returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string ReturnControl(string OperatorInsId)
        {
            string status = "1";
            try
            {
                if (!string.IsNullOrEmpty(OperatorInsId))
                {
                    ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                    DataTable dt = client.GetOperatorInstanceView(OperatorInsId);
                    if (dt.Rows.Count > 0)
                    {
                        status = "OK%@" + dt.Rows[0]["Status"].ToString();
                    }
                }

            }
            catch (Exception ex)
            {

                status = "Err%@" + ex.Message;    
            }

            return status;

        }


        /// <summary>
        /// 获取任务实例节点的类型
        /// </summary>
        /// <param name="WorkTaskInstanceId">任务实例节点ID</param>
        /// <returns>返节点类型</returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string GetWorkTaskTypeID(string WorkTaskInstanceId)
        {
            string status = "1";
            try
            {
                if (!string.IsNullOrEmpty(WorkTaskInstanceId))
                {
                    ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
                    string TaskType = client.GetWorkTaskTypeID(WorkTaskInstanceId);
                    if (!string.IsNullOrEmpty(WorkTaskInstanceId))
                    {
                        status = "OK%@" + TaskType;
                    }
              
                }

            }
            catch (Exception ex)
            {

                status = "Err%@" + ex.Message;
            }

            return status;

        }


        /// <summary>
        /// 流程任务信息提示实体
        /// </summary>
        [Serializable]
        public class WFTooltip
        {
            /// <summary>
            /// 标题
            /// </summary>
            public string title
            {
                get;
                set;
            }
            /// <summary>
            /// 任务信息
            /// </summary>
            public string TaskToWhoMsg
            {
                get;
                set;
            }
            /// <summary>
            /// 操作结果
            /// </summary>
            public string ResultMsg
            {
                get;
                set;
            }
         
        }

        /// <summary>
        /// 获取指任务实例操作结果
        /// </summary>
        /// <param name="TransmitName"></param>
        /// <param name="WorkTaskInstanceId"></param>
        /// <returns></returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string getWFTooltip(string TransmitName,string WorkTaskInstanceId)
        {
            ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient();
            WFTooltip tooltip = new WFTooltip();
            if (!string.IsNullOrEmpty(WorkTaskInstanceId))
            {
                string title = "";
                string TaskToWhoMsg = "";
                string ResultMsg = "";

                TaskToWhoMsg = client.GetTaskToWhoMsg(WorkTaskInstanceId);
                //string transmitId = System.Web.HttpContext.Current.Session["transmitId"] == null ? string.Empty : System.Web.HttpContext.Current.Session["transmitId"].ToString();    //todo zhuyun
                string transmitId = TransmitName;
                ResultMsg = client.GetResultMsg(WorkTaskInstanceId);
                DataTable dt = client.GetWorkTaskInstanceView(WorkTaskInstanceId);
         
                title = "操作结果:" + ResultMsg;
   
                if (TaskToWhoMsg.Length <= 0)
                {
                    TaskToWhoMsg = "未提交至任何人,请检查流程模板和组织机构配置是否正确!";
                    if (ResultMsg == WorkFlowConst.WorkflowOverMsg)//流程结束
                    {
                        TaskToWhoMsg = "流程结束!";
                    }
                    if (ResultMsg == WorkFlowConst.TaskBackMsg)
                    {
                        TaskToWhoMsg = WorkFlowConst.TaskBackMsg;
                    }
                }

                else
                {
                    if (!string.IsNullOrEmpty(transmitId))
                    {
                        string[] transmituser = transmitId.Split(',');
                        string[] username = TaskToWhoMsg.Split(',');
                        TaskToWhoMsg = "";
                        for (int j = 0; j < transmituser.Length; j++)
                        {
                            for (int i = 0; i < username.Length; i++)
                            {
                                if (transmituser[j].ToString() == username[i].ToString())
                                {
                                    TaskToWhoMsg += username[i].ToString();
                                }
                            }
                        }
                    }
                    //System.Web.HttpContext.Current.Session["transmitId"] = null;
                    TaskToWhoMsg = "成功提交至:" + TaskToWhoMsg + "。你已完成该任务处理,可以关闭该窗口。";
                }
                //---------------------------todo zhuyun 20121012--------------------------//
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["OperType"].ToString() == "12")
                    {
                        TaskToWhoMsg = "已成功提交,你已完成该任务处理,可以关闭该窗口。";
                    }
                }
                if (title.Contains("退回"))
                {
                    TaskToWhoMsg = "成功退回至提交人！";
                }

                tooltip.title = title;
                tooltip.TaskToWhoMsg = TaskToWhoMsg;
                tooltip.ResultMsg = ResultMsg;

            }
            
            return ZX.Common.Globals.ObjectToJSON(tooltip);
        }


        /// <summary>
        /// 指定公开课期数记录
        /// </summary>
        /// <param name="PostID"></param>
        /// <returns></returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string GetCrmProductLayout(string ProductLayoutID)
        {
            string strWorkMsg = "";
            try
            {
                if (!string.IsNullOrEmpty(ProductLayoutID))
                {
                    BCrmProductLayout bllLayout = new BCrmProductLayout();
                         IList<V_CrmProductLayout> listLayout = bllLayout.GetProductLayoutByProductLayoutId(new Guid(ProductLayoutID));
                         if (listLayout != null && listLayout.Count > 0)
                         {
                             V_CrmProductLayout cpl = listLayout[0];
                             strWorkMsg = "OK%@" + cpl.BeginDate.ToShortDateString() + "|" + cpl.EndDate.ToShortDateString() + "|" + cpl.Place;
                         }
                    
                }
            }
            catch (Exception ex)
            {
                strWorkMsg = "ERR%@" + ex.Message;
            }
            return strWorkMsg;

        }


	}
}